
package com.demo2do.boyle.client.web.controller.customer;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.client.service.SocialAccountService;
import com.demo2do.boyle.client.service.VariableService;
import com.demo2do.boyle.common.entity.AuditStatus;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.social.SocialAccount;
import com.demo2do.boyle.common.entity.customer.social.SocialType;
import com.demo2do.boyle.common.entity.system.Variable;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Secure;

/**
 * 
 * @author Wilson
 */
@Controller
@RequestMapping("/customers")
public class SocialAccountController {

    private static final Logger logger = LoggerFactory.getLogger(SocialAccountController.class);
    
    /** mapping table: variable	id **/
	private static final Integer PROPERTY_TYPE = 1;
    
    @Autowired
    private CustomerService customerService;

    @Autowired
    private SocialAccountService socialAccountService;
    
    @Autowired
    private VariableService variableService;
    
    /**
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping("/{id}/social-type")
    public String listSocialType(@Secure(property = "id") Integer customerId) {
    	
    	Result result = new Result();
    	
    	try {
    		
    		Customer customer = customerService.load(Customer.class, customerId);
    		
    		List<SocialType> socialTypes = socialAccountService.listSocialType(customer);
    		
    		result.success().data("systemSocialTypes", SocialType.values()).data("socialTypes", socialTypes);
    		
    	} catch (Exception e) {
    		logger.info("listSocialType()", e);
    		result.fail().message("服务器异常");
    	}
    	
    	return JsonUtils.toJsonString(result);
    	
    }
    
    /**
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping("/{socialAccountId}/show-social-type")
    public String showSocialTypeById(@PathVariable(value = "socialAccountId") Integer socialAccountId) {
    	
    	Result result = new Result();
    	
    	try {
    		
    		SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, socialAccountId);
    		
    		result.success().data("socialType", socialAccount != null ? socialAccount.getType().getName() : null);
    		result.success().data("link", socialAccount != null ? socialAccount.getLink() : null);
    		
    	} catch (Exception e) {
    		logger.info("listSocialType()", e);
    		result.fail().message("服务器异常");
    	}
    	
    	return JsonUtils.toJsonString(result);
    	
    }

    /**
     * list all social accounts of a customer
     * 
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/{id}/social-accounts")
    public String listSocialAccounts(@Secure(property = "id") Integer customerId) {

        Result result = new Result();

        try {
        	
        	Customer customer = customerService.load(Customer.class, customerId);
        	
            List<SocialAccount> socialAccounts = socialAccountService.list(customer);
            
            Variable variable = variableService.queryObjectForId(PROPERTY_TYPE);
            
            for (SocialAccount socialAccount : socialAccounts) {
            	socialAccount.setVariable(Integer.valueOf(variable.getValue()));
			}

            result.success().data("socialAccounts", socialAccounts);

        } catch (Exception e) {

            logger.info("listSocialAccounts()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
       
    }
    
    /**
     * load the social account
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/{customerId}/social-accounts/{id}")
    public String loadSocialAccount(@PathVariable("id") Integer id) {

        Result result = new Result();

        try {

        	SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, id);
        	int limitCycle = DateUtils.getIntervalDays(socialAccount.getUploadTime(), new Date()).size();

        	if(limitCycle>Constant.SOCIALACCOUNT_UPLOAD_LIMIT_CYCLE) {
        		socialAccount.setLimited(false);
        	} else {
        		socialAccount.setLimited(true);
        	}

    		socialAccountService.update(socialAccount);
            result.success().data("socialAccount", socialAccount);

        } catch (Exception e) {

            logger.info("loadSocialAccount()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
       
    }
    
    /**
     * 
     * @param id
     * @param socialType
     * @param account
     * @param picture
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{id}/social-accounts", method = RequestMethod.POST)
    public String createSocialAccount(@Secure(property = "id") Integer customerId,
    								  @RequestParam("socialType") String socialType,
    								  @RequestParam("account") String account,
    								  @RequestParam("picture") String picture) {

        Result result = new Result();

        try {
        	
        	Customer customer = customerService.load(Customer.class, customerId);

        	SocialAccount socialAccount= new SocialAccount(account, picture, SocialType.aliasOf(socialType), customer);
        	
            socialAccountService.save(socialAccount.initialize());

            result.success().message("添加新账户成功");

        } catch (Exception e) {

            logger.info("createSocialAccount()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
       
    }
    
    /**
     * 
     * @param id
     * @param socialType
     * @param account
     * @param picture
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{id}/modify-social-accounts", method = RequestMethod.POST)
    public String modifySocialAccount(@Secure(property = "id") Integer customerId,
    		@RequestParam("socialAccountId") String socialAccountId,
    		@RequestParam(value="link", required = false) String link,
    		@RequestParam("picture") String picture,
    		@RequestParam("socialType") String socialType) {
    	
    	Result result = new Result();
    	
    	try {
    		
    		Customer customer = customerService.load(Customer.class, customerId);
    		SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, Integer.valueOf(socialAccountId));
    		socialAccount.setAuditStatus(AuditStatus.AUDITING);
    		socialAccount.setPicture(picture);
    		socialAccount.setLink(link);
    		socialAccount.setType(SocialType.aliasOf("WECHAT".equals(socialType)?SocialType.WECHAT.getDescription():SocialType.SINA_WEIBO.getDescription()));
    		socialAccount.setCustomer(customer);
    		socialAccountService.update(socialAccount);
    		
    		result.success().message("修改账户成功");
    		
    	} catch (Exception e) {
    		
    		logger.info("createSocialAccount()", e);
    		result.fail().message("服务器异常");
    		
    	}
    	
    	return JsonUtils.toJsonString(result);
    	
    }

    /**
     * edit social account name
     * @param id
     * @param code
     * @param type
     * @param picture
     * @return
     */
	/*@RequestMapping(value="/{id}/social-accounts/{socialAccountId}/edit-name", method=RequestMethod.POST)
	@ResponseBody
	public String editName(@PathVariable("socialAccountId") Integer id,
						   @RequestParam(value = "name") String name) {
		Result result = new Result();
		
		try {
			SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, id);
			socialAccount.setName(name);
			socialAccountService.update(socialAccount);
			result.success().data("socialAccount", socialAccount).message("修改成功");
		} catch (Exception e) {
			
			logger.info("editSocialAccount()" + e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}*/
	
	/**
	 * edit social account nickname
	 * @param id
	 * @param nickname
	 * @return
	 */
	/*@RequestMapping(value="/{id}/social-accounts/{socialAccountId}/edit-nickname", method=RequestMethod.POST)
	@ResponseBody
	public String editNickname(@PathVariable("socialAccountId") Integer id,
									@RequestParam(value = "nickname") String nickname) {
		Result result = new Result();
		
		try {
			SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, id);
			socialAccount.setNickName(nickname);
			socialAccountService.update(socialAccount);
			result.success().data("socialAccount", socialAccount).message("修改成功");
		} catch (Exception e) {
			
			logger.info("editSocialAccount()" + e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}*/
	
	/**
	 * edit social account link
	 * @param id
	 * @param link
	 * @return
	 */
	/*@RequestMapping(value="/{id}/social-accounts/{socialAccountId}/edit-link", method=RequestMethod.POST)
	@ResponseBody
	public String editLink(@PathVariable("socialAccountId") Integer id,
									@RequestParam(value = "link") String link) {
		Result result = new Result();
		
		try {
			SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, id);
			socialAccount.setLink(link);
			socialAccountService.update(socialAccount);
			result.success().data("socialAccount", socialAccount).message("修改成功");
		} catch (Exception e) {
			
			logger.info("editSocialAccount()" + e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}*/
	
	@RequestMapping(value="/{id}/social-accounts/{socialAccountId}/edit-picture", method=RequestMethod.POST)
	@ResponseBody
	public String editPicture(@PathVariable("socialAccountId") Integer id,
									@RequestParam(value = "picture") String picture) {
		Result result = new Result();
		
		try {
			SocialAccount socialAccount = socialAccountService.load(SocialAccount.class, id);
			socialAccountService.update(socialAccount.reUpload(picture));
			result.success().data("socialAccount", socialAccount).message("上传成功");
		} catch (Exception e) {
			
			logger.info("editSocialAccountPicture()" + e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}

}
